package com.exposit.zbs.dao.base;

import org.hibernate.*;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;


/**
 * This abstract class is for base Dao-layer operations.
 *
 * @param <T>  Type of Entity
 * @param <PK> Type of primary key.
 * @author Andrey
 */
@Repository
@Transactional
public abstract class BaseDAO<T, PK extends Serializable> implements IBaseDAO<T, PK> {

	@Autowired
	protected SessionFactory sessionFactory;

	@Override
	public List<T> findAll() {

		Criteria cr = getSession().createCriteria(this.getGenericEntityClass());
		return (List<T>) cr.list();
	}

	/**
	 * This methor returns current session from session factory.
	 *
	 * @return Current session.
	 */
	protected Session getSession() {

		return sessionFactory.getCurrentSession();
	}

	protected Class<T> getGenericEntityClass() {

		ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
		return (Class<T>) parameterizedType.getActualTypeArguments()[0];
	}

	@Override
	public T findById(PK id) {

		return (T) getSession().get(this.getGenericEntityClass(), id);
	}

	@Override
	public void update(T o) {

		getSession().update(o);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void delete(T persistentObject) {

		try {
			getSession().delete(persistentObject);
		} catch (NonUniqueObjectException e) {
			// in a case of detached object
			T instance = (T) getSession().merge(persistentObject);
			getSession().delete(instance);
		}
	}

	@Override
	public PK save(T savedEntity) {

		return (PK) getSession().save(savedEntity);
	}

	@Override
	public List<T> findByCriteria(Criterion... criterion) {

		Criteria crit = getSession().createCriteria(this.getGenericEntityClass());
		for (Criterion c : criterion) {
			crit.add(c);
		}
		return (List<T>) crit.list();
	}

	@Override
	public void delete(PK id) {

		T persistentObject = (T) getSession().load(this.getGenericEntityClass(), id);
		try {
			getSession().delete(persistentObject);
		} catch (NonUniqueObjectException e) {
			// in a case of detached object
			T instance = (T) getSession().merge(persistentObject);
			getSession().delete(instance);
		}
	}

	@Override
	public List<T> executeNamedQueryList(String name, Map<String, String> params) {

		Query query = getSession().getNamedQuery(name);
		for (String key : params.keySet()) {
			query.setString(key, params.get(key));
		}
		return query.list();
	}

	public T executeNamedQuery(String name, Map<String, String> params) {

		Query query = getSession().getNamedQuery(name);
		for (String key : params.keySet()) {
			query.setString(key, params.get(key));
		}
		return (T) query.uniqueResult();
	}
}
